余烬缀记

TypeScript 泛型传参的理解

edited on:

今天在实现一个需要传递泛型类型然后又需要根据泛型推导类型的函数,结果这个函数在接受泛型传参后死活再泛型推导时死活不兼容,仔细想了下,应该是泛型在手动传递时便不会再进行推导了

示例代码:

const a = <
  T extends any = any,
  B extends boolean = true,
  R extends T | undefined = B extends true ? T : T | undefined
>(
  v: B = true as B // not use "as" will trigger type argument assign error
): R => '' as R;

const x = a<string>(); // ok! type is string
const y = a<string>(false); // error! but type is string | undefined

很奇怪,类型推导出来了但是还是报了TS2345: Argument of type 'false' is not assignable to parameter of type 'true | undefined'.这个错